package com.entities.user.servlets;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.core.managers.LoginManager;
import com.core.protocols.IServiceLayerDelegate;
import com.core.servlets.TaskTrackerServlet;
import com.core.utils.GlobalConstants;
import com.entities.user.servicelayer.UserListLayer;

/**
 * Servlet implementation class ProjectDelete
 */

public class UserResetPassword
        extends TaskTrackerServlet
        implements IServiceLayerDelegate {

	private HttpServletRequest  httpRequest  = null;
	private HttpServletResponse httpResponse = null;



	@Override
	public <T> void responseResponseItemsList ( final List <T> items,
	                                            final Object request,
	                                            final Exception exception ) {

		if ( httpResponse == null ) {
			return;
		}

		if ( exception != null ) {
		}

		LoginManager loginManager = LoginManager.sharedInstance();
		try {
			loginManager.doDefaultRedirection(this.httpRequest, this.httpResponse);
		} catch ( IOException e ) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	private static final long serialVersionUID = 1L;



	@Override
	protected void doPost ( HttpServletRequest request,
	                        HttpServletResponse response )
	        throws ServletException, IOException {

		this.httpRequest = request;
		this.httpResponse = response;

		Integer userId = null;
		try {
			userId = Integer.parseInt(request.getParameter(GlobalConstants.SERVLET_PARAM_KEY));
		} catch ( NumberFormatException e ) {
			userId = null;
		}

		String redirectionBack = null;
		if ( userId == null ) {
			redirectionBack = String.format("%s", GlobalConstants.SERVLET_DASHBOARD);
		} else {
			redirectionBack = String.format("%s?id=%d", GlobalConstants.SERVLET_USERRESETPASSWORD, userId);
		}


		String confirmUserPassword = request.getParameter("confirmUserPassword");
		String newPassword = request.getParameter("userPassword");
		if ( confirmUserPassword == null ) {
			response.sendRedirect(redirectionBack);
			return;
		}
		if ( !confirmUserPassword.equals(newPassword) ) {
			response.sendRedirect(redirectionBack);
			return;
		}

		UserListLayer userListLayer = new UserListLayer();
		userListLayer.setLayerDelegate(this);
		userListLayer.resetPassword(userId, newPassword, this);

	}


}
